package com.whosly.mysql.protocol.packet.impl;

import com.whosly.mysql.protocol.code.MysqlProtocolException;
import com.whosly.mysql.protocol.jdbc.MySQLMessage;
import io.netty.buffer.ByteBuf;
import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;

/**
 * @author fengyang(yueny09 @ 163.com)
 */
@Slf4j
public class QueryCommandPacket extends NettyCommandPacket
{
    /**
     * 编码后的查询语句
     */
    public String query;

    /**
     * 原始字符串, 原始字节可以直接取  getArg()
     *
     * 有些场景需要保留原始字符串，比如插入二进制流字节
     *
     * Some scenes need to retain the original string, such as insert binary stream bytes
     */
    public String queryWithoutEncoding;

    @Override
    public void read(byte[] bodyBytes) {
        read(bodyBytes, null);
    }

    public void read(byte[] bodyBytes, String charset) {
        readBody(bodyBytes);

        this.queryWithoutEncoding = new String(getArg());
        try {
            this.query = (charset == null ?
                    new String(getArg()) :
                    new String(getArg(), charset));
        } catch (UnsupportedEncodingException e) {
            log.error("QUERY COMMAND PACKET error:", e);
        }
    }

    @Override
    protected void readBody(byte[] bodyBytes) {
        MySQLMessage mm = new MySQLMessage(bodyBytes);

        setCmd(mm.read());
        setArg(mm.readBytes());
    }

    @Override
    public ByteBuf writeBuf(ByteBuf buffer)
    {
        throw new MysqlProtocolException("QueryCommandPacket writeBuf is UnSupport!");
    }

    protected void writeBody(ByteBuf buffer) {
        throw new MysqlProtocolException("QueryCommandPacket writeBuf is UnSupport!");
    }

}
